package MTT::Controller::Templates;
use Moose;
use namespace::autoclean;

BEGIN {extends 'Catalyst::Controller'; }

=head1 NAME

MTT::Controller::Templates - Catalyst Controller

=head1 DESCRIPTION

Catalyst Controller.

=head1 METHODS

=cut


=head2 index

=cut

use utf8;
use Data::Dumper;

use POSIX qw(strftime);
use MTT::Libs::Report;

sub index :Path :Args(0) {
    my ( $self, $c ) = @_;

	my $templates = $self->get_templates($c);
	my @users = $c->model('DBIC::User')->all();

	$c->stash(
		template => 'templates.tt2',
		templates => $templates,
		users => \@users
	);
}


sub delete: Local : Args(1) {
	my($self, $c, $id_report) = @_;

	my $report = $c->model('DBIC::Report')->find($id_report);
	if ($report) {
		unless ($report->id_user == $c->user->id || $c->check_user_roles('admin') ) {
			$c->dispatch('/access_denied');
		}

		$c->model('DBIC::ReportStore')->search({id_report => $id_report})->delete();
		$report->delete();
		$c->user_log->info('Удален шаблон ' . $report->name, 'templates');
	}

	$c->response->redirect('/templates');
}

sub get_templates {
	my ($self, $c, $id_user, $limit) = @_;

	unless ( $id_user || $c->check_user_roles('admin') ) {
		$id_user = $c->user->id;
		die 'user id need' unless $id_user;
	}

	my $reps = $c->model('DBIC::Report')->search(
		{
			($id_user ? (id_user => $id_user) : ())
		},
		{
			order_by => { -desc => 'date_create' },
			( $limit ? (rows => $limit) : () )
		}
	);

	my @reports;
	while ( my $report = $reps->next ) {
		my $rep = {};
		$rep->{name} = $report->name;
		$rep->{date_create} = $report->date_create;
		$rep->{comment} = $report->comment;

		unless ($id_user) {
			$rep->{fio} = $report->id_user->fio;
		}

		$rep->{id_report} = $report->id;
		
		my @args;
		my $rs = $report->report_stores->search({type => 'id_type'})->next();
		if ($rs) {
			push @args, $rs->value;
		}

		$rs = $report->report_stores->search({type => 'id_switch'})->next();
		if ($rs && @args) {
			push @args, $rs->value;
		}

		$rep->{url} = $c->uri_for('/reports', @args, {id_report => $report->id});

		push @reports, $rep;
	}

	return \@reports;

}


sub transmit : Local : Args(1) {
	my ($self, $c, $id_report) = @_;

	my $id_user = $c->req->query_params->{id_user};

	if ($id_report && $id_user) {
		if ( my $report = $c->model('DBIC::Report')->find($id_report) ){
			if ($id_user != $report->id_user) {
				$report->copy({
						id_user => $id_user
					});

				$c->user_log->info('Передан шаблон ' . $report->name . ' пользователю ' . $id_user, 'templates');
			}
		}
	}

	$c->response->redirect('/templates');
}
=head1 AUTHOR

A clever guy

=head1 LICENSE

This library is free software. You can redistribute it and/or modify
it under the same terms as Perl itself.

=cut

__PACKAGE__->meta->make_immutable;

1;
